package com.ruoyi.web.controller.app;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.system.domain.AppGroupInfo;
import com.ruoyi.system.domain.AppGroupUser;
import com.ruoyi.system.domain.AppUser;
import com.ruoyi.system.service.IAppGroupInfoService;
import com.ruoyi.system.service.IAppGroupUserService;
import com.ruoyi.system.service.IAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app/neteaseGroup")
@Api("APP群组接口")
public class ForAppNeteaseGroupController extends BaseController {

    @Autowired
    private IAppGroupInfoService groupInfoService;
    @Autowired
    private IAppUserService userService;
    @Autowired
    private IAppGroupUserService groupUserService;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @PostMapping("createNeteaseGroup")
    @ApiOperation("创建群组")
    public AjaxResult createNeteaseGroup(@ApiIgnore @ApiParam("userId") Long userId, @ApiParam("群组id") @RequestParam String groupId, @ApiParam("群组名称") @RequestParam String groupName, @ApiParam("群类型，0：普通群，1：特殊群") @RequestParam Integer type, Integer kind, @ApiParam("群头像") String faceUrl, @ApiParam("邀请的群成员列表") String members) {
        AppGroupInfo groupInfoEntity = new AppGroupInfo();
        groupInfoEntity.setGroupId(groupId);
        groupInfoEntity.setCreateTime(new Date());
        groupInfoEntity.setIsExit(1);
        groupInfoEntity.setUserId(getUserId());
        groupInfoEntity.setType(type);
        if (type == 1) {
            if (kind == null) return AjaxResult.error(-1, "创建特殊群必须传特殊群种类");
            AppUser createUser = userService.getById(getUserId());
            if (createUser.getHasLot() > 0) return AjaxResult.error(-1, "用户没有创建特殊群权限");
            groupInfoEntity.setKind(kind);
        }
        groupInfoEntity.setGroupName(groupName);
        groupInfoEntity.setFaceUrl(faceUrl);
        groupInfoEntity.setIsAddMember(1);
        groupInfoEntity.setFreezeState(0);
        return groupInfoService.createGroup(groupInfoEntity, members);
    }


    @PostMapping("getGroupInfoById")
    @ApiOperation("根据群组GroupId获取群信息")
    public AjaxResult getGroupInfoById(@ApiParam("群组id") @RequestParam String groupId) {
        Map<String, Object> map = new HashMap<>();
        map.put("groupInfo", groupInfoService.getOne(new QueryWrapper<AppGroupInfo>().eq("group_id", groupId)));
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("getGroupFreezeState")
    @ApiOperation("获取群冻结状态")
    public AjaxResult getGroupFreezeState(@ApiParam("群组id") @RequestParam String groupId) {
        QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupId);
        AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("freezeState", groupEntity.getFreezeState());
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("getGroupSet")
    @ApiOperation("获取群设置接口")
    public AjaxResult getGroupSet(@ApiParam("群组id") @RequestParam String groupId) {
        QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupId);
        AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
        groupEntity.setGroupName(CommonUtils.decodeNickname(groupEntity.getGroupName()));

        /**
         * 获取带V标签群成员列表
         */
        QueryWrapper<AppGroupUser> groupUserWrapper = new QueryWrapper<>();
        groupUserWrapper.eq("group_id", groupId);
        groupUserWrapper.eq("label_state", 1);
        List<AppGroupUser> groupUserList = groupUserService.list(groupUserWrapper);
        String groupUserIds = "";
        for (AppGroupUser groupUser : groupUserList) {
            groupUserIds += groupUser.getUserId().toString() + ",";
        }
        if (groupUserIds.length() > 0) {
            groupUserIds = groupUserIds.substring(0, groupUserIds.length() - 1);
            groupEntity.setGroupMemberIds(groupUserIds);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("groupEntity", groupEntity);
        return AjaxResult.ok(0, "", map);
    }

    @PostMapping("removeTeam")
    @ApiOperation("解散群")
    public AjaxResult removeTeam(@ApiIgnore @ApiParam("userId") Long userId, @ApiParam("群组id") @RequestParam String groupId) {
        QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", getUserId());
        wrapper.eq("group_id", groupId);
        AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
        if (groupEntity == null) {
            return AjaxResult.error(-1, "群组id不存在或用户非群主");
        }
        return groupInfoService.removeGroup(groupEntity);
    }

    @PostMapping("changeOwner")
    @ApiOperation("移交群主")
    public AjaxResult changeOwner(@ApiIgnore @ApiParam("userId") Long userId, @ApiParam("群组id") @RequestParam String groupId, @ApiParam("新群主id") @RequestParam Long newGroupOwnerId) {
        QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", getUserId());
        wrapper.eq("group_id", groupId);
        AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
        if (groupEntity == null) {
            return AjaxResult.error(-1, "群组id不存在或用户非群主");
        }
        groupEntity.setUserId(newGroupOwnerId);
        groupInfoService.updateById(groupEntity);
        return AjaxResult.ok(0, "", null);
    }

    @PostMapping("addGroupMember")
    @ApiOperation("添加群成员")
    public AjaxResult addGroupMember(@ApiParam("群组id") @RequestParam String groupId,
                                     @ApiParam("成员ids") @RequestParam String members) {
        QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupId);
        AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
        if (groupEntity == null) {
            return AjaxResult.error(-1, "群组id不存在");
        }
        return groupInfoService.addGroupMember(groupId, members);
    }


    @PostMapping("addAdminGroupMember")
    @ApiOperation("群添加，群成员")
    public AjaxResult addAdminGroupMember(@ApiParam("群组id") @RequestParam String groupId,
                                          @ApiParam("成员ids") @RequestParam String members) {
        Boolean isAdd = tencentCloudImUtil.addAdminGroupMember(groupId, members);
        if (isAdd) {
            QueryWrapper<AppGroupInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("group_id", groupId);
            AppGroupInfo groupEntity = groupInfoService.getOne(wrapper);
            if (groupEntity == null) {
                return AjaxResult.error(-1, "群组id不存在");
            }
            return groupInfoService.addGroupMember(groupId, members);
        }
        return AjaxResult.error(-1, "操作失败");
    }

    @PostMapping("delGroupMember")
    @ApiOperation("踢出群成员")
    public AjaxResult delGroupMember(@ApiParam("群组id") @RequestParam String groupId, @ApiParam("成员ids") @RequestParam String members) {
        QueryWrapper<AppGroupUser> groupUserWrapper = new QueryWrapper<>();
        groupUserWrapper.eq("group_id", groupId);
        JSONArray memberArr = JSONArray.parseArray(members);

        groupUserWrapper.in("user_id", memberArr);
        groupUserService.remove(groupUserWrapper);
        return AjaxResult.ok(0, "", null);
    }

    @PostMapping("managementGroupAdministrator")
    @ApiOperation("群主增加或删除管理员")
    public AjaxResult managementGroupAdministrator(@ApiParam("群组id") @RequestParam String groupId, @ApiParam("管理员id") @RequestParam String userId, @ApiParam("类型, add:新增 del:删除") @RequestParam String type) {
        Boolean result = tencentCloudImUtil.managementGroupAdministrator(groupId, userId, type);
        if (result) {
            return AjaxResult.ok(0, "操作成功", null);
        }
        return AjaxResult.ok(-1, "操作失败", null);
    }

    @PostMapping("managementGroupForbidSenMsg")
    @ApiOperation("批量禁言和取消禁言")
    public AjaxResult managementGroupForbidSenMsg(@ApiParam("群组id") @RequestParam String groupId, @ApiParam("成员ids") @RequestParam String members, @ApiParam("类型, add:批量禁言 del:取消禁言") @RequestParam String type) {
        Boolean result = tencentCloudImUtil.managementGroupForbidSenMsg(groupId, members, type);
        if (result) {
            return AjaxResult.ok(0, "操作成功", null);
        }
        return AjaxResult.ok(-1, "操作失败", null);
    }

    @PostMapping("getGroupMutedAccount")
    @ApiOperation("获取被禁言群成员列表")
    public AjaxResult getGroupMutedAccount(@ApiParam("群组id") @RequestParam String groupId) {
        JSONArray result = tencentCloudImUtil.getGroupMutedAccount(groupId);
        if (result == null) {
            return AjaxResult.ok(-1, "操作失败", null);
        }
        List<AppUser> list = Lists.newArrayList();
        for (int i = 0; i < result.size(); i++) {
            AppUser appUser = userService.getOne(new QueryWrapper<AppUser>().eq("account", result.getJSONObject(i).getString("Member_Account")));
            list.add(appUser);
        }
        return AjaxResult.ok(0, "获取成功", list);
    }


    @PostMapping("groupWithdrawalMessage")
    @ApiOperation("撤回群消息")
    public AjaxResult groupWithdrawalMessage(@ApiParam("群组id") @RequestParam String groupId, @RequestParam Long msgSeq) {
        Boolean result = tencentCloudImUtil.groupMsgRecall(groupId, msgSeq);
        if (!result) {
            return AjaxResult.ok(-1, "操作失败", null);
        }
        return AjaxResult.ok(0, "操作成功", null);
    }

    @PostMapping("changeGroupHideState")
    @ApiOperation("修改群的隐藏显示状态")
    public AjaxResult changeGroupHideState(@ApiParam("群组id") @RequestParam Long groupId,
                                           @ApiParam("是否隐藏 1 隐藏 2 显示") @RequestParam Integer isHide) {
        AppGroupInfo groupEntity = groupInfoService.selectAppGroupInfoById(groupId);
        groupEntity.setIsHide(isHide);
        groupInfoService.updateAppGroupInfo(groupEntity);
        return AjaxResult.ok(0, "获取成功",null);
    }
}
